//
//  sprite.cpp
//  PixelDudes
//
//  Created by Noah Figg on 3/23/13.
//  Copyright (c) 2013 PixelDudes. All rights reserved.
//

#include "sprite.h"
#include "utility.h"
#include "game_engine.h"
#include "SDL_gfx/SDL_rotozoom.h"
#include <sstream>

Sprite::Sprite(std::string imageName, bool alphaFormat) : RenderTarget(std::string("sprite_") + (imageName = format_path(imageName)))
{
	//std::stringstream logLine;
	//logLine << "Sprite(): resourceName: " << imageName << " alpha: " << alphaFormat;
	//log_info(logLine.str());
	//Init vars
	resourceName = imageName;
	centered = false;
	this->alphaFormat = alphaFormat;
	unmanagedImage = NULL;
	getIdComp()->addTag("sprite");
	reversed = false;
}

void Sprite::setResource(std::string imageName, bool alphaFormat)
{
	//std::stringstream logLine;
	//logLine << "Sprite::SetResourceName(): " << imageName << " alpha: " << alphaFormat;
	//log_info(logLine.str());
	//Update vars
	resourceName = format_path(imageName);
	getIdComp()->id = std::string("sprite_") + imageName;
	this->alphaFormat = alphaFormat;
	unmanagedImage = NULL; //Clear unmanaged image when setting resource name
}

std::string Sprite::getResource()
{
	return resourceName;
}

void Sprite::setUnmanagedImage(SDL_Surface* image)
{
	resourceName = ""; //Clear resource name when setting unmanged image
	unmanagedImage = image;
}

Sprite::~Sprite()
{
	//std::stringstream logLine;
	//logLine << "~Sprite(): resourceName: " << resourceName;
	//log_info(logLine.str());
}

SDL_Surface* Sprite::getRenderImage()
{
	if (resourceName.size() > 0) //If resourceName is set, get image for our resourceName
	{
		if (!reversed)
		{
			return GameEngine::getResources()->GetImage(resourceName, alphaFormat);
		}
		else
		{
			std::string revName = resourceName + ":mirrorX";
			SDL_Surface* image = GameEngine::getResources()->GetImage(revName, alphaFormat);
			if (image == NULL) //Reverse image not setup in res. manager
			{
				image = zoomSurface(GameEngine::getResources()->GetImage(resourceName, alphaFormat), -1.0, 1.0, 0);
				GameEngine::getResources()->SetImage(revName, image);
			}
			return image;
		}
	}
	else //Otherwise, return the unmanagedImage whether it is NULL or not.
		return unmanagedImage;
}

void Sprite::Render(SDL_Surface* screen)
{
	Sint16 sx, sy;

	SDL_Surface* img = NULL;
	//Get image to render
	img = getRenderImage();
	if (img != NULL)
	{
		getScreenCoords(sx, sy);

		apply_surface(sx, sy, img, screen);
    
	}
	//Render children
    RenderTarget::Render(screen);
}

PD_vect2 Sprite::getSize()
{
	PD_vect2 dim;
	dim.x = dim.y = 0.0;

	SDL_Surface* image = GameEngine::getResources()->GetImage(resourceName, true);
	if (image != NULL)
	{
		dim.x = image->w;
		dim.y = image->h;
	}
	return dim;
}

void Sprite::getScreenCoords(Sint16 &x, Sint16 &y)
{
	SDL_Surface* img = NULL;
	//Get image to render
	img = getRenderImage();
	RenderTarget::getScreenCoords(x, y);
	if (centered) {
		x = x - (img->w / 2);
		y = y - (img->h / 2);
	}
}
